package heman.server.controllers;



import heman.server.database.DatabaseController;
import heman.server.entities.Player;
import heman.server.entities.PlayerManager;
import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.debug.Debug;
import ks.server.interfaces.IProcessServerMessage;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * 
 *  Controller to handle ban. 
 *  
 *  <request version="1.0" id="589a39591271844e3fbe32bbb9281ad9">
 *  <ban player="129382" allow="false"/>
 *  </request>
 *    @author Wenlong Liu
 *  */

public class BanController implements IProcessServerMessage {

	public boolean process(Communicator com, Message m) {
		String originator=m.getOriginator();
		
       
        Node root = m.contents();
        NamedNodeMap map=root.getAttributes();

        Node player=map.
        		getNamedItem("player");
        Node allowNode=map.
        		getNamedItem("allow");
        if (player ==null ||allowNode==null) return false;
        String playerID=player.getNodeValue();
        boolean b=Boolean.parseBoolean(allowNode.getNodeValue());
        boolean ret=false;
        
        if (b)
        	return DatabaseController.unBan(playerID);
        else {
        	ret=DatabaseController.ban(playerID);
        	if (!ret) return false;
        	//have Successfully banned the player
        	//Check if the player is still online
        	Player p=PlayerManager.getInstance().getPlayer(playerID);
        	if (p==null) return true;
        	else{
        		 // produce logoutResponse.
        		 StringBuilder sb = new StringBuilder(Message.responseHeader(true));
        		 sb.append("<logoutResponse player=\"");
        	        sb.append(p.getId());
        	        sb.append("\"/></response>");
        	        Document d = Message.construct (sb.toString());
        	        
        	        // send to all clients...
        	        Message r = new Message (d);
        	    
        	        r.setOriginator(originator);
        	        r.setRecipient(originator);
        	        r.setBroadcast();
        	        //remove the player
        	        PlayerManager.getInstance().removePlayer(p);
        	        return com.distribute(r);
        	}
        		
        }

        
	}
}